<template>
  <div class="course-list-container">
    <h2 class="page-title">课程管理</h2>
    
    <el-card shadow="never" class="toolbar-card">
      <el-button type="primary" icon="Plus" @click="$router.push('/course/create')">新增课程</el-button>
      <el-button icon="Refresh" @click="loadList">刷新</el-button>
    </el-card>
    
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="list" stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="封面" width="100">
          <template #default="{ row }">
            <div v-if="row.coverImage || row.cover" class="cover-wrapper">
              <el-image
                :src="row.coverImage || row.cover"
                fit="cover"
                class="course-cover"
                :preview-src-list="[row.coverImage || row.cover]"
                preview-teleported
                hide-on-click-modal
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div v-else class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称" min-width="200" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="instructor" label="讲师" width="120" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            {{ row.price > 0 ? `¥${row.price}` : '免费' }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长(分钟)" width="110" />
        <el-table-column prop="participants" label="报名人数" width="100" />
        <el-table-column prop="rating" label="评分" width="80" />
        <el-table-column prop="isRecommended" label="推荐" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isRecommended === 1 ? 'success' : 'info'" size="small">
              {{ row.isRecommended === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="$router.push(`/course/edit/${row.id}`)">编辑</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="loadList"
          @current-change="loadList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const loadList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.COURSE_LIST, {
      params: { page: currentPage.value, pageSize: pageSize.value }
    })
    if (response.code === 200) {
      list.value = response.data.list || response.data || []
      total.value = response.data.total || list.value.length
    }
  } catch (error) {
    console.error('加载课程列表失败:', error)
    ElMessage.error('加载课程列表失败')
  } finally {
    loading.value = false
  }
}

const handleStatusChange = async (row) => {
  if (!row || !row.id) {
    ElMessage.error('课程ID不存在，无法更新状态')
    return
  }
  
  try {
    const response = await request.put(`${API_ENDPOINTS.COURSE_UPDATE}/${row.id}`, { 
      status: row.status 
    })
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个课程吗？', '提示', { type: 'warning' })
    const response = await request.delete(`${API_ENDPOINTS.COURSE_DELETE}/${row.id}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadList()
    }
  } catch (error) {
    if (error !== 'cancel') console.error('删除失败:', error)
  }
}

onMounted(() => loadList())
</script>

<style scoped>
.course-list-container { padding: 0; }
.page-title { font-size: 24px; font-weight: bold; color: #333; margin: 0 0 20px 0; }
.toolbar-card { margin-bottom: 20px; }
.table-card { margin-top: 20px; }
.pagination-container { display: flex; justify-content: flex-end; margin-top: 20px; }

.cover-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

.course-cover {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 60px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
  border-radius: 4px;
}
</style>

